<template>
  <div>
    <home-header></home-header>
    <home-swiper :swiperList="swiperList"></home-swiper>
    <home-icon :iconList="iconList"></home-icon>
    <home-recommend :recommendList="recommendList"></home-recommend>
    <home-weekend :weekendList="weekendList"></home-weekend>
  </div>
</template>

<script>
import HomeHeader from './components/Header'
import HomeSwiper from './components/Swiper'
import HomeIcon from './components/Icon'
import HomeRecommend from './components/Recommend'
import HomeWeekend from './components/Weekend'
import aixos from 'axios'
import { mapState } from 'vuex'
export default {
  name: 'Home',
  components: {
    HomeHeader,
    HomeSwiper,
    HomeIcon,
    HomeRecommend,
    HomeWeekend
  },
  data () {
    return {
      swiperList: [],
      iconList: [],
      recommendList: [],
      weekendList: [],
      // lastCity用于当Home页面的city变化时重新发出ajax请求
      lastCity: ''
    }
  },
  computed: {
    ...mapState(['city'])
  },
  methods: {
    getHomeInfo () {
      aixos.get('/api/index.json?city=' + this.city)
        .then(this.getHomeInfoSucc)
    },
    getHomeInfoSucc (res) {
      // res.data就是ajax里的json对象
      res = res.data
      // console.log(res)
      if (res.ret && res.data) {
        const data = res.data
        this.swiperList = data.swiperList
        this.iconList = data.iconList
        this.recommendList = data.recommendList
        this.weekendList = data.weekendList
      }
    }
  },
  // 一般页面每一次跳转都要重新渲染，使得mounted每次都触发。
  // 当App.vue用keepalive包裹时，页面会被缓存。页面切换时直接从缓存中获取，导致mounted只执行一开始的那一次
  mounted () {
    this.lastCity = this.city
    this.getHomeInfo()
  },
  // 当App.vue用keepalive包裹时，会生成一个activated的钩子函数。在每次页面跳转时触发，即将你页面已缓存，不触发mounted，也会触发activated
  activated () {
    if (this.lastCity !== this.city) {
      this.lastCity = this.city
      this.getHomeInfo()
    }
  }
}
// 单页应用，页面切换快(实际只是用js改了DOM)，但是首页展示慢，SEO差(搜索引擎差，百度时总是展示在众多结果的最后面)
// 多页应用，首页展示快，SEO优，但是页面切换慢。
</script>
